package fastjson.code;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: JSON的使用
 *
 * @author code-worker
 * @date 2021/08/17 22:11
 */
public class JsonDemo {
    private String demoName;
    private String demoDesc;
    @Override
    public String toString() {
        return "JsonDemo{" +
                "demoName='" + demoName + '\'' +
                ", demoDesc='" + demoDesc + '\'' +
                '}';
    }
    JsonDemo(){}
    JsonDemo(String demoName, String demoDesc) {
        this.demoName = demoName;
        this.demoDesc = demoDesc;
    }
    public String getDemoName() {
        return demoName;
    }
    private void setDemoName(String demoName) {
        this.demoName = demoName;
    }
    public String getDemoDesc() {
        return demoDesc;
    }
    private void setDemoDesc(String demoDesc) {
        this.demoDesc = demoDesc;
    }

    public static void main(String[] args) {
        JsonDemo demo = new JsonDemo("demo", "示例demo");
        System.out.println("单个对象的相关操作：");
        System.out.println("\t不使用fastJson转换字符串："+demo.toString());
        String jsonString = JSON.toJSONString(demo);
        System.out.println("\t使用fastJson将对象转换为json字符串："+jsonString);
        JSONObject jsonObject = JSON.parseObject(jsonString);
        System.out.println("\t使用fastJson将json字符串转换为json对象："+jsonObject);
        JsonDemo jsonDemo = JSON.parseObject(jsonString, JsonDemo.class);
        System.out.println("\t使用fastJson将json字符串转换为指定类型对象："+jsonDemo);

        List<JsonDemo> demoList = new ArrayList<>();
        JsonDemo demo2 = new JsonDemo();
        demo2.setDemoName("demo2");
        demoList.add(demo2);
        JsonDemo demo3 = new JsonDemo();
        demo3.setDemoDesc("示例demo3");
        demoList.add(demo3);
        System.out.println("\n集合对象的相关操作");
        System.out.println("不使用fastJson转换字符串："+demoList.toString());
        String demoListString = JSON.toJSONString(demoList);
        System.out.println("\t使用fastJson将集合对象转换为json字符串："+demoListString);
        JSONArray demoListObject = JSON.parseArray(demoListString);
        System.out.println("\t使用fastJson将json字符串转换为json集合对象："+demoListObject);
        List<JsonDemo> jsonDemoList = JSON.parseArray(demoListString, JsonDemo.class);
        System.out.println("\t使用fastJson将json字符串转换为指定类型集合对象:"+ jsonDemoList);
        Type type = new TypeReference<List<JsonDemo>>() {}.getType();
        List<JsonDemo> list = JSON.parseObject(demoListString, type);
        System.out.println("\t使用fastJson将json字符串转换为指定类型集合对象(方式二):"+list);
    }
}
